﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;

namespace Baggr
{
    public static class CollectionHelper
    {
        private const int GuidSizeInBytes = 16;
        public static byte[] Serialize(this IEnumerable<Guid> collection)
        {
            var collectionSize = collection.Count();
            if (collectionSize == 0)
                return null;

            var result = new byte[collectionSize * GuidSizeInBytes];
            var resultIndex = 0;
            foreach (var guidBytes in collection.Select(guid => guid.ToByteArray()))
            {
                Debug.Assert(GuidSizeInBytes == guidBytes.Length, "Size of Guid should be " + GuidSizeInBytes);
                Array.Copy(guidBytes, 0, result, resultIndex, GuidSizeInBytes);
                resultIndex += GuidSizeInBytes;
            }
            return result;
        }
        public static IEnumerable<Guid> Desirialize(byte[] serialized)
        {
            using (var stream = new MemoryStream(serialized))
            {
                var bf = new BinaryFormatter();
                var result = bf.Deserialize(stream) as IEnumerable<Guid>;
                return result;
            }
        }
    }
}
